package com.hzw.saas.web.app.group.aspect;

import java.util.ArrayList;
import java.util.List;

import com.hzw.saas.api.group.IGroupMemberService;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.security.pojo.dto.SaasUser;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.common.util.SpringELUtils;
import com.hzw.saas.service.group.annotation.GroupAuthBefore;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 检查资源权限
 *
 * @author zzl
 * @since 03/07/2021
 */
@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class GroupAuthCheck {

    private final HttpStatus forbidden = HttpStatus.FORBIDDEN;

    private final IGroupMemberService groupMemberService;

    @Before("@annotation(groupAuthBefore)")
    @SuppressWarnings("unchecked")
    public void checkFileOwnAuthBeforeInvoke(JoinPoint joinPoint, GroupAuthBefore groupAuthBefore) {
        List<String> groupIdList = new ArrayList<>();
        if (StrUtil.isNotBlank(groupAuthBefore.groupId())) {
            String fileId = SpringELUtils.getSpelValue(joinPoint, groupAuthBefore.groupId(), String.class);
            if (StrUtil.isNotBlank(fileId)) {
                groupIdList.add(fileId);
            }
        }
        if (StrUtil.isNotBlank(groupAuthBefore.groupIds())) {
            List<String> fileIds = SpringELUtils.getSpelValue(joinPoint, groupAuthBefore.groupIds(), List.class);
            if (CollectionUtil.isNotEmpty(fileIds)) {
                fileIds.removeIf(StrUtil::isBlank);
                groupIdList.addAll(fileIds);
            }
        }
        for (String groupId : groupIdList) {
            this.checkGroupMember(groupId);
        }
    }

    private void checkGroupMember(String groupId) {
        SaasUser saasUser = SecurityUtils.getUser();
        boolean member = groupMemberService.tryJoinGroup(saasUser.getUserId(), groupId);
        AssertUtil.assertThrow("无此群组操作权限: " + groupId, forbidden, !member);
    }


}
